from flask import jsonify, request
from datetime import datetime
from decimal import Decimal
from commons.controller.base_controller import BaseController
from commons.entity.po.travel import Travel
from travel_service.travel.service.travel_service import TravelService


class TravelController(BaseController):
    def __init__(self):
        self.travel_service = TravelService()

    def get_travel_by_id(self):
        """
        根据出差ID获取出差信息。
        """
        # 从请求体解析参数
        data = request.get_json()
        travel_id = data.get("travelId")

        return BaseController.get_success_response(self, self.travel_service.get_travel_by_travel_id(travel_id))

    def get_travel_by_user_id(self):
        """
        根据用户ID获取出差信息。
        """
        # 从请求体解析参数
        data = request.get_json()
        user_id = data.get("userId")

        return BaseController.get_success_response(self, self.travel_service.get_travel_by_user_id(user_id))

    def get_all_travels_by_id_list(self):
        """
        根据出差ID列表获取出差信息。
        """
        # 从请求体解析参数
        data = request.get_json()
        travel_id_list = data.get("travelIdList")
        travels = self.travel_service.get_all_travels_by_id_list(
            travel_id_list)

        return jsonify([travel.to_dict() for travel in travels])

    def get_final_travel_list_by_user_id(self):
        """
        根据UserId查询travelList（这是筛选后的）
        """
        # 从请求体解析参数
        data = request.get_json()
        user_id = data.get("userId")
        travels = self.travel_service.get_final_travel_list_by_user_id(
            user_id)

        return jsonify([travel.to_dict() for travel in travels])

    def add_travel(self):
        """
        添加新的出差记录
        """
        print("add_travel")
        # 从请求体解析参数
        data = request.get_json()

        # 获取并验证必要的参数
        travel_reason = data.get("travelReason")
        travel_detail = data.get("travelDetail")
        apply_date_str = data.get("applyDate")
        start_date_str = data.get("startDate")
        end_date_str = data.get("endDate")
        food_cost = data.get("foodCost")
        transport_cost = data.get("transportCost")
        hotel_cost = data.get("hotelCost")
        cost_detail = data.get("costDetail")
        advance_payment = data.get("advancePayment")
        user_id = data.get("userId")

        print(type(apply_date_str))
        print(start_date_str)
        print(end_date_str)
        try:
            # 转换applyDate为datetime格式
            apply_date = datetime.strptime(apply_date_str.split(' (')[0], "%a %b %d %Y %H:%M:%S GMT%z")  # Assuming "YYYY-MM-DD" format
            start_date = datetime.strptime(start_date_str.split(' (')[0], "%a %b %d %Y %H:%M:%S GMT%z")  # Assuming "YYYY-MM-DD" format
            end_date = datetime.strptime(end_date_str.split(' (')[0], "%a %b %d %Y %H:%M:%S GMT%z")  # Assuming "YYYY-MM-DD" format

            # 转换 BigDecimal（传输为字符串类型）为 Decimal
            food_cost = Decimal(food_cost)
            transport_cost = Decimal(transport_cost)
            hotel_cost = Decimal(hotel_cost)

            # 创建Reimbursement对象
            travel = Travel(
                travel_reason=travel_reason,
                travel_detail=travel_detail,
                apply_date=apply_date,
                start_date=start_date,
                end_date=end_date,
                food_cost=food_cost,
                transport_cost=transport_cost,
                hotel_cost= hotel_cost,
                cost_detail= cost_detail,
                advance_payment= advance_payment,
                user_id= user_id
            )

            # 调用服务层添加报销记录
            # self.travel_service.add(travel)

            # 返回成功响应
            return BaseController.get_success_response(self.travel_service.add(travel))

        except ValueError as e:
            # 如果日期或数字转换失败
            return BaseController.get_server_error_response(None)
